package com.tian.service.impl;

import com.tian.common.CommonResult;
import com.tian.config.ThreadPollTaskSchedulerService;
import com.tian.dto.*;
import com.tian.entity.ChargeRecord;
import com.tian.entity.ChargeStationGun;
import com.tian.entity.ChargeStationInfo;
import com.tian.enums.ChargerGunStatusEnum;
import com.tian.enums.ChargingStatusEnum;
import com.tian.enums.ChargingPayStatusEnum;
import com.tian.enums.ResultCode;
import com.tian.mapper.ChargeRecordMapper;
import com.tian.mapper.ChargeStationGunMapper;
import com.tian.mapper.ChargeStationInfoMapper;
import com.tian.service.ChargeRecordService;
import com.tian.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * {@code @description:} 充电记录服务实现类
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-12-13 9:41
 * {@code @version:} 1.0
 */
@Service
@Slf4j
public class ChargeRecordServiceImpl implements ChargeRecordService {
    @Resource
    private ChargeRecordMapper chargeRecordMapper;
    @Resource
    private ChargeStationGunMapper chargeStationGunMapper;
    @Resource
    private ChargeStationInfoMapper chargeStationInfoMapper;
    @Resource
    private ThreadPollTaskSchedulerService threadPollTaskSchedulerService;

    @Override
    public CommonResult<Boolean> startCharge(ChargingStartReqDto chargingStartReqDto) {
        if (StringUtil.isEmpty(chargingStartReqDto.getGunNo())) {
            log.error("gunNo参数不能为空");
            return CommonResult.failed(ResultCode.PARAMETER_EMPTY.getCode(), "gunNo参数不能为空");
        }
        ChargeStationGun chargeGun = chargeStationGunMapper.selectByGunNo(chargingStartReqDto.getGunNo());
        if (chargeGun == null) {
            log.error("接受到消息中gunNo有误，request parameter={}", chargingStartReqDto);
            return CommonResult.failed(ResultCode.PARAMETER_EMPTY.getCode(), "gunNo参数有误");
        }
        if (chargeGun.getStatus() != ChargerGunStatusEnum.IDLE.getChargerStatus()) {
            String byStatus = ChargerGunStatusEnum.getByStatus(chargeGun.getStatus());
            log.error("枪{}正在{}中，不能使用", chargeGun.getGunNo(), byStatus);
            return CommonResult.failed(ResultCode.GUN_ERROR);
        }
        int isExists = chargeRecordMapper.checkRecordExists(chargeGun.getId());
        if (isExists == 1) {
            log.error("枪{}正在充电中，不能重复充电", chargeGun.getGunNo());
            return CommonResult.failed(ResultCode.GUN_USING);
        }
//        ChargeUserLoginResDto user = UserCacheUtil.getUser();
//        Long userId = user.getId();
        String gunNo = chargingStartReqDto.getGunNo();
        String[] split = gunNo.split("-");
        Long userId = Long.parseLong(split[1]);
        ChargeStationInfo charger = chargeStationInfoMapper.selectByPrimaryKey(chargeGun.getStationId());

        ChargeRecord chargerRecord = new ChargeRecord();
        chargerRecord.setStationGunId(chargeGun.getId());
        chargerRecord.setUserId(userId);
        chargerRecord.setPayStatus(ChargingPayStatusEnum.INIT.getPayStatus());
        chargerRecord.setPrice(charger.getPrice());
        chargerRecord.setStartTime(new Date());
        chargerRecord.setCreateTime(new Date());
        chargerRecord.setQuantity(BigDecimal.ZERO);
        chargerRecord.setChargeStatus(ChargerGunStatusEnum.CHARGING.getChargerStatus());
        chargeRecordMapper.insert(chargerRecord);
        threadPollTaskSchedulerService.startTask(chargeGun.getGunNo());
        return CommonResult.success(Boolean.TRUE);
    }

    @Override
    public CommonResult<Boolean> stopCharge(ChargingStopReqDto chargingStopReqDto) {
        ChargeRecord chargeRecord = chargeRecordMapper.selectByPrimaryKey(chargingStopReqDto.getChargingRecordId());
        if (chargeRecord == null) {
            log.error("充电记录不存在，request parameter={}", chargingStopReqDto);
            return CommonResult.failed("充电记录不存在");
        }
        if (chargeRecord.getChargeStatus() != ChargerGunStatusEnum.CHARGING.getChargerStatus()) {
            log.error("充电记录{}的充电状态不是CHARGING，已充电结束", chargeRecord.getId());
            return CommonResult.success();
        }
        ChargeStationGun chargeGun = chargeStationGunMapper.selectByPrimaryKey(chargeRecord.getStationGunId());

        threadPollTaskSchedulerService.stopTask(chargeGun.getGunNo());
        chargeRecord.setEndTime(new Date());
        chargeRecord.setChargeStatus(ChargingStatusEnum.CHARGED.getStatus());
        BigDecimal price = chargeRecord.getPrice();
        BigDecimal quantity = chargeRecord.getQuantity();
        chargeRecord.setAmount(price.multiply(quantity));
        chargeRecordMapper.updateByPrimaryKey(chargeRecord);
        return CommonResult.success(Boolean.TRUE);
    }

    /**
     * 模拟充电数据上报
     */
    @Override
    public void chargingDataReport(Integer stationGunId) {
        //        RBucket<String> chargeStationGunBucketByNo = redissonClient.getBucket(StationRedisPreKey.STATION_GUN_NO_PRE_KEY + gunNo);
//        ChargeStationGun chargeStationGun = JSON.parseObject(chargeStationGunBucketByNo.get(), ChargeStationGun.class);
        ChargeRecord chargeRecord = chargeRecordMapper.selectByChargeGunId(stationGunId);
        chargeRecord.setQuantity(chargeRecord.getQuantity().add(new BigDecimal("0.2")));
        int i = chargeRecordMapper.updateByPrimaryKey(chargeRecord);
        if (i > 0) {
            log.info("充电数据上报成功：{}", chargeRecord);
        }
    }
}
